// import * as schedule from "node-schedule";
import * as fs from "fs";
// import { getStat } from "../utils/fs";
import path from "path";
import { fileURLToPath } from "url";
// import { success, fail } from "../utils/base";
// import { getTimestampToType } from "../utils/time";

import type { Stats } from "fs";

// 默认查询-时间范围
let defaultInfoTime = 3;

/**
 * @description: 这里查询日志
 * 1. 分页查询
 * 2. 默认时间范围: 最近 3 天
 * 3. 查询 某个路由的 pv 曝光量
 * 4.
 */
export default defineEventHandler(async (event) => {
  // 获取请求参数 post
  const body = await readBody(event);
  // 获取当前文件的 Path
  const __filename = fileURLToPath(import.meta.url);
  // console.log("获取当前文件：", __filename);
  // 获取当前文件所在的目录
  const __dirname = path.dirname(__filename);
  // console.log("当前目录：", __dirname);
  const parnentDir = path.dirname(__dirname);
  // console.log("上一级目录：", parnentDir);
  // 声明写入路径
  const writePath = `${parnentDir}/public/log`;
  const filePath = `${writePath}/page-puv.json`;
  // 获取文件大小
  if (body.getsize == 1) {
    let fileSize = 0;
    const stat: Stats = (await getStat(
      body.filename ? `${writePath}/${body.filename}.json` : filePath!
    )) as Stats;
    if (stat.size > 0) {
      fileSize = stat.size / 1024 / 1024 + 1;
    }
    return success(`文件:${fileSize}M`);
  }
  // 操作数据
  let isHas;
  try {
    const stat: Stats = (await getStat(filePath)) as Stats;
    isHas = !!stat;
  } catch (error) {
    return fail("路径不存在,暂无数据");
  }

  if (isHas) {
    // 校验参数的正确性
    if (!body.pageNumber || !body.pageSize) {
      return fail(`pageNumber,pageSize参数错误`);
    }
    // 读取文件数据
    const read = () => {
      return new Promise((resolve, reject) => {
        fs.readFile(filePath, "utf8", (error, jsonString) => {
          if (error) {
            console.log("❌读取失败", error);
            return reject(false);
          }
          const fileData = JSON.parse(jsonString);
          fileData.total = fileData.list.length;

          // 时间倒序
          // if (fileData.list.length > 2) {
          //   fileData.list = fileData.list.sort((a: any, b: any) => {
          //     return b.data.time - a.data.time;
          //   });
          // }

          // 根据时间范围-过滤
          let beginTime = body.beginTime;
          let endTime = body.endTime;
          if (!beginTime) {
            beginTime = Date.now() - defaultInfoTime * 24 * 60 * 60 * 1000;
          }
          if (!endTime) {
            endTime = Date.now();
          }

          fileData.list = fileData.list.filter((e: any) => {
            return e.data.trackTime >= beginTime && e.data.trackTime <= endTime;
          });
          fileData.total = fileData.list.length;

          // 根据 path 页面路由,来查找数据源
          //  pv 曝光量
          if (body.path) {
            fileData.list = fileData.list.filter((e: any) => {
              if (
                e.data.cusData &&
                e.data.cusData.to &&
                e.data.cusData.to.path
              ) {
                const regex = /^\/[^/]+\/[^/]+(\/.*)$/; // 匹配前两个路径段，捕获后面的部分
                const match = e.data.cusData.to.path.match(regex);

                if (match && match[1] && match[1] == body.path) {
                  return true;
                } else {
                  return false;
                }
              }
              return false;
            });
            // 统计类型如果是: UV, 则需要去重
            if (body.statisticalType && body.statisticalType == "UV") {
              const dataMap = new Map(
                fileData.list.map((item: any) => [
                  item.authInfo.trackerId,
                  item,
                ])
              );
              // 将 Map 转换回数组（如果需要）
              fileData.list = Array.from(dataMap.values());
            }
            fileData.total = fileData.list.length;
          }

          // 根据统计粒度, 小时
          let pointInfo: any = {}; // key 时间戳   value pv数量
          if (body.granularity) {
            if (body.granularity == "hour") {
              // 获取每个小时的整点时间戳
              const hours = getTimestampToType(beginTime, endTime) || [];
              // 遍历,查找数量
              fileData.list.forEach((e: any) => {
                const key = hours.findIndex(
                  (t) => Number(e.data.trackTime) <= Number(t)
                );

                if (hours[key]) {
                  if (pointInfo[`${hours[key]}`]) {
                    pointInfo[`${hours[key]}`] += 1;
                  } else {
                    pointInfo[`${hours[key]}`] = 1;
                  }
                }
              });
            } else if (body.granularity == "day") {
              // 获取最近 x 个月,每天 23 点 59 分 59 秒的时间戳
              const months = getTimestampToType(beginTime, endTime, 24) || [];
              // console.log("months", months);
              // 遍历,查找数量
              fileData.list.forEach((e: any) => {
                const key = months.findIndex((t) => e.data.trackTime <= t);
                if (months[key]) {
                  if (pointInfo[`${months[key]}`]) {
                    pointInfo[`${months[key]}`] += 1;
                  } else {
                    pointInfo[`${months[key]}`] = 1;
                  }
                }
              });
            }
          }

          // 根据 errorId 过滤
          // if (body.errorId) {
          //   fileData.list = fileData.list.filter((e: any) => {
          //     return e.data.errorId == body.errorId;
          //   });
          //   fileData.total = fileData.list.length;
          // }

          // 根据分页返回数据
          if (fileData.list && fileData.list.length > 0) {
            if (fileData.list.length > (body.pageNumber - 1) * body.pageSize) {
              let results = [];
              if (body.isCallList) {
                results = fileData.list.slice(
                  (body.pageNumber - 1) * body.pageSize,
                  body.pageNumber * body.pageSize
                );
              }

              resolve({
                create: fileData.create,
                total: fileData.total,
                list: results,
                pointInfo,
              });
            } else {
              resolve({
                create: fileData.create,
                list: [],
                total: fileData.total,
                pointInfo,
              });
            }
          } else {
            resolve({
              create: fileData.create,
              list: [],
              total: fileData.total,
              pointInfo,
            });
          }
          // resolve(fileData);
        });
      });
    };
    try {
      const json = await read();
      return success(json);
    } catch (error) {
      return fail(error);
    }
  } else {
    return fail("文件未创建,暂无数据");
  }
});
